import React, { useMemo } from 'react';
import { NavLink } from 'react-router-dom'; // 导入 NavLink 组件
import { Menu } from 'antd';
import {
  AppstoreOutlined,
  ContainerOutlined,
  DesktopOutlined,
  MailOutlined,
  PieChartOutlined,
  HomeOutlined,
  BarsOutlined,
  ToolOutlined,
  UserOutlined,
  SafetyOutlined,
  AreaChartOutlined,
  BarChartOutlined,
  LineChartOutlined,
  WindowsOutlined
} from '@ant-design/icons';
import menuConfig from '../../config/menuConfig';
import logo from '../../assets/images/logo.png';
import './index.less';

const { SubMenu } = Menu; // 从 antd 的 Menu 组件中解构出 SubMenu，用于创建子菜单。

// 根据指定菜单数据列表生成 Menu 的子节点数组
const getMenuNodes = (menuList) => {
  return menuList.reduce((pre, item) => {
    // 处理无子菜单的菜单项
    if (!item.children) {
      const IconComponent = getIconComponent(item.icon);
      pre.push((
        <Menu.Item key={item.key}>
          <NavLink to={item.key} activeClassName="active"> {/* 使用 NavLink 并设置 activeClassName */}
            <IconComponent />
            <span>{item.title}</span>
          </NavLink>
        </Menu.Item>
      ));
    } else { // 处理有子菜单的菜单项
      const IconComponent = getIconComponent(item.icon);
      pre.push((
        <SubMenu
          key={item.key}
          title={
            <span>
              <IconComponent />
              <span>{item.title}</span>
            </span>
          }
        >
          {getMenuNodes(item.children)}
        </SubMenu>
      ));
    }
    return pre;
  }, []);
};

// 根据图标名称获取对应的图标组件
const getIconComponent = (iconName) => {
  switch (iconName) {
    case 'appstore':
      return AppstoreOutlined;
    case 'container':
      return ContainerOutlined;
    case 'desktop':
      return DesktopOutlined;
    case 'mail':
      return MailOutlined;
    case 'pie-chart':
      return PieChartOutlined;
    case 'home':
      return HomeOutlined;
    case 'bars':
      return BarsOutlined;
    case 'tool':
      return ToolOutlined;
    case 'user':
      return UserOutlined;
    case 'safety':
      return SafetyOutlined;
    case 'area-chart':
      return AreaChartOutlined;
    case 'bar-chart':
      return BarChartOutlined;
    case 'line-chart':
      return LineChartOutlined;
    case 'windows':
      return WindowsOutlined;
    default:
      return AppstoreOutlined;
  }
};

const LeftNav = () => {
  // 使用 useMemo 缓存菜单节点，避免每次渲染都重新生成
  const menuNodes = useMemo(() => {
    return getMenuNodes(menuConfig);
  }, []);

  return (
    <div className="left-nav">
      <NavLink to='/admin/home' className='logo-link' activeClassName="active">
        <img src={logo} alt="logo" />
        <h1>硅谷后台</h1>
      </NavLink>
      <Menu
        mode="inline" // 垂直排列菜单
        theme="dark"
      >
        {menuNodes}
      </Menu>
    </div>
  );
};

export default LeftNav;
